package com.evolve.autotest.actions;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

public class ActionsLoader {

	private static final Logger logger = Logger.getLogger(ActionsLoader.class);
	
	/**
	 * This will load all the test cases in the directory Actions should be
	 * placed in the directory where they belong. For example Shell scripts
	 * should be placed in the directory "scripts" Other scripts should be
	 * placed in a directory of the type It will also load all the actions in
	 * subfolders.
	 * 
	 * @param actionsDir
	 * @return List of IAction. If directory is empty or faulty a empty list
	 *         will be returned
	 */
	public List<IAction> loadActions(String actionsDir) {

		logger.info("Loading actions");
		
		List<IAction> actions = loadActionsInDirectories(actionsDir);
		
		logger.info("Finished loading " + actions.size() + " actions");
		
		return actions;
	}

	private List<IAction> loadActionsInDirectories(String actionsDir) {
		List<IAction> actionsList = new LinkedList<IAction>();

		if (actionsDir == null || actionsDir.length() == 0) {
			logger.error("Unable to load actions. The actions directory was not a directory: " + actionsDir);
			return actionsList;
		}

		File directory = new File(actionsDir);

		if (!directory.exists() || directory.isFile()) {
			logger.error("Unable to load actions. The actions directory was not a directory: " + actionsDir);
			return actionsList;
		}

		File[] files = directory.listFiles();

		if (files == null) {
			return actionsList;
		}

		IAction action;

		for (File file : files) {
			if (file.isFile()) {
				
				action = new ScriptAction(file);
				
				actionsList.add(action);
				
			} else {
				// File is directory
				loadActionsInDirectories(file.getAbsolutePath());
			}
		}

		return actionsList;
	}
}
